package com.itany.ems.servlet;

import com.itany.ems.exception.RequestParameterErrorException;
import com.itany.ems.exception.ServiceException;
import com.itany.ems.service.EmpService;
import com.itany.ems.service.impl.EmpServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author 石小俊
 * @date 2024年05月24日 18:53
 */
@WebServlet("*.emp")
public class EmpServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String path = request.getServletPath();
        switch (path) {
            case "/add.emp":
                addEmp(request, response);
                break;
            case "/findAll.emp":
                findAll(request, response);
                break;
            default:
                PrintWriter out = response.getWriter();
                out.println("<h1 style='color:red;'>您输入的地址有误,请重新输入</h1>");
        }
    }

    public void addEmp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        EmpService empService = new EmpServiceImpl();
        String name = request.getParameter("name");
        String salary = request.getParameter("salary");
        String gender = request.getParameter("gender");
        String edu = request.getParameter("edu");
        String[] hobbies = request.getParameterValues("hobbies");

        try {
            empService.addEmp(name, salary, gender, edu, hobbies);
            response.sendRedirect(request.getContextPath() + "/findAll.emp");
        } catch (RequestParameterErrorException e) {
            request.setAttribute("empMsg",e.getMessage());
            request.getRequestDispatcher("/ems/addEmp.jsp").forward(request,response);
        } catch (ServiceException e) {
            request.setAttribute("empMsg",e.getMessage());
            request.getRequestDispatcher("/ems/addEmp.jsp").forward(request,response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("empMsg","服务器内部异常");
            request.getRequestDispatcher("/ems/addEmp.jsp").forward(request,response);
        }
    }

    public void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/ems/empList.jsp").forward(request,response);
    }

}
